home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17088 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  57.2 KB

  1. Path: sun.soe.clarkson.edu!cline
  2. From: cline@sun.soe.clarkson.edu (Marshall Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ: posting #1/4
  5. Followup-To: comp.lang.c++
  6. Date: 13 Apr 1996 17:40:55 GMT
  7. Organization: Paradigm Shift, Inc (technology consulting)
  8. Sender: cline@sun.soe.clarkson.edu
  9. Distribution: world
  10. Expires: +1 month
  11. Message-ID: <4koov7$l5t@library.erc.clarkson.edu>
  12. Reply-To: cline@parashift.com (Marshall Cline)
  13. NNTP-Posting-Host: sun.soe.clarkson.edu
  14. Summary: Please read this before posting to comp.lang.c++
  15. Archive-name: C++-faq/part1_4
  16.  
  17. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  18. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  19. Posting 1 of 4.
  20.  
  21. UPDATED 5/96:
  22.  * Added two more FAQs on including C header files (currently FAQ 112 & 113).
  23.  * Updated the FAQ on pure virtual functions (near FAQ-77).
  24.  * Updated the FAQ on "delete this" (near FAQ-39).
  25.  
  26. UPDATED 4/96:
  27.  * Added European mirror site for the WWW addresses:
  28.     http://www.informatik.uni-konstanz.de/~kuehl/cpp/cppfaq.htm
  29.  
  30. UPDATED 3/96:
  31.  * Added a FAQ on whether C++ is better than Ada (or Visual Basic or ...)
  32.  * Added WWW and anonymous ftp addresses:
  33.     http://www.connobj.com/cpp/cppfaq.htm
  34.     ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.c++/
  35.  * Added a new FAQ on heterogeneous containers
  36.  * Modified the FAQs covering coding standards
  37.  * Added an Acronyms section for things like ARM, C++PL2, etc.
  38.  * Updated the dynamic-typing FAQs to reflect dynamic_cast and typeid()
  39.  * Updated the ftp address for C++2LaTeX
  40.  * Added a new LaTeX macro for pretty-printing the name "C++"
  41.  * Added a paragraph in the FAQ on mixing new and free, or malloc and delete
  42.  * Corrected an error in the on-line location for the ANSI-C++ draft standard
  43.  * Corrected a access-level error in FAQ 45.
  44.  * Added a note to FAQ 129
  45.  * Fixed the "iostream vs stdio" FAQ
  46.  * Fixed a typo in FAQ 111
  47.  * Corrected numerous typographical errors
  48.  
  49. UPDATED 1/96:
  50.  * Anonymous ftp fron.soe.clarkson.edu still does not work.
  51.  * No significant changes were made this month.
  52.  
  53. UPDATED 9/95:
  54.  * Added FAQ 41 on using a variable for the first dimension of a
  55.    multi-dimensional array
  56.  * Added FAQ 123 on the code from "Numerical Recipes"
  57.  * Added section 20 ("Libraries").  It's still pretty sparse, but it's a start
  58.  * Fixed a bug in FAQ 30 (there was no variable "i")
  59.  * Added FAQ 124 on dynamic linking to avoid bloated executables
  60.  * Added FAQ 32 on trying to "reopen" cin and cout in binary mode
  61.  * Added the access info to get the ANSI/ISO Committee Draft via ftp (FAQ 7)
  62.  
  63. UPDATED 7/95:
  64.  * Minor stuff (but not change in FTP access, below).
  65.  
  66. UPDATED 6/95:
  67.  * Corrected the mailing address where the ANSI-C++ Draft can be ordered
  68.  * Added a FAQ on floating point [Thanks to Phil Staite]
  69.  * Added a FAQ on multidimensional arrays [Thanks to Doug Shapter]
  70.  * Added a FAQ on interrupt service routines and ptrs to member functions
  71.  * Reorganized the FAQ on allocating all objects of a certain class via 'new'
  72.  
  73. UPDATED 5/95:
  74.  * Minor cosmetic changes
  75.  
  76. UPDATED 4/95:
  77.  * Added a question on a common BC++ Windows issue
  78.  * Fixed the ftp address for NIHCL
  79.  * Added an explanation that "ARM" is short for "Annotated Reference Manual"
  80.  
  81. UPDATED 3/95:
  82.  * Added a question on "delete this"
  83.  * Added two questions on iostreams and eof
  84.  * Fixed the entry on "c-mode" and "cc-mode" in Gnu emacs
  85.  
  86. UPDATED 1/95:
  87.  * A Chinese version of this document has been produced; details below.
  88.  
  89. UPDATED 12/94:
  90.  * Added a FAQ on STL (currently #115).
  91.  * Added a FAQ on name mangling (currently #119).
  92.  * Fixed typo in FAQ that compared composition with private inheritance.
  93.  * Corrected some spelling errors.
  94.  
  95. UPDATED 11/94:
  96.  * Added differentiator between "FAQ book" and "FAQ posting"
  97.  * Other cosmetic changes
  98.  
  99. UPDATED 10/94:
  100.  * Fixed a few typos
  101.  
  102. UPDATED 9/94:
  103.  * Minor cosmetic changes
  104.  
  105. UPDATED 8/94:
  106.  * Made it up-to-date with respect to "typeid" and "dynamic_cast".
  107.  * Made it up-to-date with respect to "mutable" and "const_cast".
  108.  * Rewrote most of the answers to provide general cleanup.
  109.  * The quotation marks are now "..." rather than `...' or ``...''
  110.  * Sample code lines start with a tab; no other lines starts with a tab.
  111.  * Everything was edited; minor modifications everywhere.
  112.  
  113. ==============================================================================
  114. SECTION 1: Introduction and table of contents
  115. ==============================================================================
  116.  
  117.     DOCUMENT:    Frequently-Asked-Questions for comp.lang.c++
  118.     REVISION:    Apr 13, 1996
  119.  
  120.     POSTING!=BOOK:    This C++ FAQ posting is NOT the same as the "FAQ book".
  121.             The "FAQ book" ("C++ FAQs", Addison-Wesley, 1995) is
  122.             5x larger than this posting.  See below for more.
  123.  
  124.     AUTHOR:        Marshall P. Cline, Ph.D.
  125.             Paradigm Shift, Inc.
  126.             One Park St. / Norwood, NY  13668
  127.             voice: 315-353-6100
  128.             fax:   315-353-6110
  129.             email: cline@parashift.com
  130.  
  131.     COPYRIGHT:    Copyright (C), 1991-96 Marshall P. Cline, Ph.D.
  132.             Permission to copy all or part of this work is granted,
  133.             provided that the copies are not made or distributed
  134.             for resale (except a nominal copy fee may be charged),
  135.             and provided that the AUTHOR, COPYRIGHT, & NO WARRANTY
  136.             sections are retained verbatim and are displayed
  137.             conspicuously.  If anyone needs other permissions that
  138.             aren't covered by the above, please contact the author.
  139.  
  140.     NO WARRANTY:    THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR
  141.             PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR
  142.             IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH
  143.             RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY
  144.             PARTICULAR PURPOSE.
  145.  
  146.     AVAILABILITY:    http://www.connobj.com/cpp/cppfaq.htm
  147.             http://www.informatik.uni-konstanz.de/~kuehl/cpp/cppfaq.htm
  148.             ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.c++/
  149.  
  150.     SEE ALSO:    comp.lang.c FAQ appears every month in that newsgroup,
  151.             and is maintained by Steve Summit (scs@eskimo.com).
  152.  
  153.     CHINESE TRANSLATION: A Chinese translation, encoded in "Big5" code
  154.             (a 16-bit Chinese code used mostly in Taiwan)
  155.             is now available for anonymous ftp at:
  156.          ftp://ftp.cis.nctu.edu.tw/Documents/News/comp.lang.c++/c-cppfaq.*
  157.  
  158. ==============================================================================
  159. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  160. ==============================================================================
  161.  
  162. Q1: Where can I download the C++ FAQ?
  163.  
  164. In US/Canada/Mexico:
  165.     http://www.connobj.com/cpp/cppfaq.htm
  166.  
  167. In Europe:
  168.     http://www.informatik.uni-konstanz.de/~kuehl/cpp/cppfaq.htm
  169.  
  170. Straight text version via FTP:
  171.     ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.c++/
  172.  
  173. ==============================================================================
  174.  
  175. Q2: Is there a C++FAQ book I can buy in a bookstore?
  176.  
  177. Yes.  "C++ FAQs" by Cline and Lomow, Addison-Wesley, 1995, ISBN 0-201-58958-3.
  178.  
  179. ==============================================================================
  180.  
  181. Q3: Why would I spend good money on a book when I can download it for free?
  182.  
  183. Because the book contains five times more material than this on-line document.
  184.  
  185. Many people have asked about the relationship between the book ("C++ FAQs",
  186. ISBN 0-201-58958-3) and this on-line document.  Some have wondered whether the
  187. posting is equivalent to the book.
  188.  
  189. The "FAQ book" is loosely based on the same concepts as this on-line document.
  190. However the FAQ book is approximately five (5) times bigger than this on-line
  191. document.  For example, the book's discussisons are much more detailed than in
  192. the on-line document, and the variety of FAQs is much wider in the book.  The
  193. book also includes thousands of cross references, external references, and
  194. index terms, as well as many programming examples.
  195.  
  196. ==============================================================================
  197. SUBSECTION 1B: Table of Contents
  198. ==============================================================================
  199.  
  200. ========== POSTING #1 ==========
  201.  
  202. SECTION 1: Introduction and table of contents
  203. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  204. Q1: Where can I download the C++ FAQ?
  205. Q2: Is there a C++FAQ book I can buy in a bookstore?
  206. Q3: Why would I spend good money on a book when I can download it for free?
  207. SUBSECTION 1B: Table of Contents
  208. SUBSECTION 1C: Nomenclature, Acronyms, and Common Abbreviations
  209.  
  210. SECTION 2: How should I post something? (READ BEFORE POSTING)
  211. Q4: Which newsgroup should I post my questions?
  212. Q5: How do I post a question about code that doesn't work correctly?
  213.  
  214. SECTION 3: Environmental/managerial issues
  215. Q6: What is OOP?  What is C++?
  216. Q7: Is C++ better than Ada? (or Pascal, C, FORTRAN, Visual Basic, or any other
  217.    language?)
  218. Q8: What are some advantages of C++?
  219. Q9: Who uses C++?
  220. Q10: Are there any C++ standardization efforts underway?
  221. Q11: Where can I get a copy of the latest ANSI/ISO-C++ draft standard?
  222. Q12: Is C++ backward compatible with ANSI-C?
  223. Q13: How long does it take to learn C++?
  224.  
  225. SECTION 4: Basics of the paradigm
  226. Q14: What is a class?
  227. Q15: What is an object?
  228. Q16: What is a reference?
  229. Q17: What happens if you assign to a reference?
  230. Q18: How can you reseat a reference to make it refer to a different object?
  231. Q19: When should I use references, and when should I use pointers?
  232. Q20: What's the deal with inline functions?
  233.  
  234. SECTION 5: Constructors and destructors
  235. Q21: What's the deal with constructors?
  236. Q22: How can I make a constructor call another constructor as a primitive?
  237. Q23: What's the deal with destructors?
  238.  
  239. SECTION 6: Operator overloading
  240. Q24: What's the deal with operator overloading?
  241. Q25: What operators can/cannot be overloaded?
  242. Q26: Can I create a "**" operator for "to-the-power-of" operations?
  243.  
  244. SECTION 7: Friends
  245. Q27: What is a "friend"?
  246. Q28: Do "friends" violate encapsulation?
  247. Q29: What are some advantages/disadvantages of using friend functions?
  248. Q30: What does it mean that "friendship is neither inherited nor transitive"?
  249. Q31: Should my class declare a member function or a friend function?
  250.  
  251. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  252. Q32: How can I provide printing for a "class Fred"?
  253. Q33: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  254. Q34: Why does my input seem to process past the end of file?
  255. Q35: Why is my program ignoring my input request after the first iteration?
  256. Q36: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?
  257.  
  258. ========== POSTING #2 ==========
  259.  
  260. SECTION 9: Freestore management
  261. Q37: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  262. Q38: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  263.    alloc'd with "malloc()"?
  264. Q39: Why should I use "new" instead of trustworthy old malloc()?
  265. Q40: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  266. Q41: How do I allocate / unallocate an array of things?
  267. Q42: What if I forget the "[]" when "delete"ing array allocated via "new
  268.    Fred[n]"?
  269. Q43: Is it legal (and moral) for a member function to say "delete this"?
  270. Q44: How do I allocate multidimensional arrays using new?
  271. Q45: Does C++ have arrays whose length can be specified at run-time?
  272. Q46: How can I ensure objects of my class are always created via "new" rather
  273.    than as locals or global/static objects?
  274.  
  275. SECTION 10: Debugging and error handling
  276. Q47: How can I handle a constructor that fails?
  277. Q48: How should I handle resources if my constructors may throw exceptions?
  278.  
  279. SECTION 11: Const correctness
  280. Q49: What is "const correctness"?
  281. Q50: Should I try to get things const correct "sooner" or "later"?
  282. Q51: What is a "const member function"?
  283. Q52: What do I do if I want to update an "invisible" data member inside a
  284.    "const" member function?
  285. Q53: Does "const_cast" mean lost optimization opportunities?
  286.  
  287. SECTION 12: Inheritance
  288. Q54: Is inheritance important to C++?
  289. Q55: When would I use inheritance?
  290. Q56: How do you express inheritance in C++?
  291. Q57: Is it ok to convert a pointer from a derived class to its base class?
  292. Q58: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  293. Q59: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  294.    bad?
  295. SUBSECTION 12A: Inheritance -- Virtual functions
  296. Q60: What is a "virtual member function"?
  297. Q61: How can C++ achieve dynamic binding yet also static typing?
  298. Q62: Should a derived class replace ("override") a non-virtual fn from a base
  299.    class?
  300. Q63: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  301. SUBSECTION 12B: Inheritance -- Conformance
  302. Q64: Should I hide public member fns inherited from my base class?
  303. Q65: Is a "Circle" a kind-of an "Ellipse"?
  304. Q66: Are there other options to the "Circle is/isnot kind-of Ellipse"
  305.    dilemma?
  306. Q67: But I have a Ph.D. in Mathematics, and I'm SURE a Circle is a kind of an
  307.    Ellipse!  Does this mean Marshall Cline is stupid?  Or that C++ is stupid?  Or
  308.    that OO is stupid?
  309. Q68: But my problem doesn't have anything to do with circles and ellipses, so
  310.    what good is that silly example to me?
  311. SUBSECTION 12C: Inheritance -- Access rules
  312. Q69: Why can't my derived class access "private" things from my base class?
  313. Q70: What's the difference between "public:", "private:", and "protected:"?
  314. Q71: How can I protect subclasses from breaking when I change internal parts?
  315. SUBSECTION 12D: Inheritance -- Constructors and destructors
  316. Q72: When my base class's constructor calls a virtual function, why doesn't my
  317.    derived class's override of that virtual function get invoked?
  318. Q73: Does a derived class destructor need to explicitly call the base
  319.    destructor?
  320. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  321. Q74: How do you express "private inheritance"?
  322. Q75: How are "private inheritance" and "composition" similar?
  323. Q76: Which should I prefer: composition or private inheritance?
  324. Q77: Should I pointer-cast from a "privately" derived class to its base
  325.    class?
  326. Q78: How is protected inheritance related to private inheritance?
  327. Q79: What are the access rules with "private" and "protected" inheritance?
  328.  
  329. SECTION 13: Abstraction
  330. Q80: What's the big deal of separating interface from implementation?
  331. Q81: How do I separate interface from implementation in C++ (like Modula-2)?
  332. Q82: What is an ABC ("abstract base class")?
  333. Q83: What is a "pure virtual" member function?
  334. Q84: How can I provide printing for an entire hierarchy of classes?
  335. Q85: When should my destructor be virtual?
  336. Q86: What is a "virtual constructor"?
  337.  
  338. ========== POSTING #3 ==========
  339.  
  340. SECTION 14: Style guidelines
  341. Q87: What are some good C++ coding standards?
  342. Q88: Are coding standards necessary?  Are they sufficient?
  343. Q89: Should our organization determine coding standards from our C
  344.    experience?
  345. Q90: Should I declare locals in the middle of a fn or at the top?
  346. Q91: What source-file-name convention is best? "foo.C"? "foo.cc"? "foo.cpp"?
  347. Q92: What header-file-name convention is best? "foo.H"? "foo.hh"? "foo.hpp"?
  348. Q93: Are there any lint-like guidelines for C++?
  349.  
  350. SECTION 15: Keys for Smalltalk programmers to learn C++
  351. Q94: Why does C++'s FAQ have a section on Smalltalk? Is this
  352.    Smalltalk-bashing?
  353. Q95: What's the difference between C++ and Smalltalk?
  354. Q96: What is "static typing", and how is it similar/dissimilar to Smalltalk?
  355. Q97: Which is a better fit for C++: "static typing" or "dynamic typing"?
  356. Q98: How can you tell if you have a dynamically typed C++ class library?
  357. Q99: How do you use inheritance in C++, and is that different from Smalltalk?
  358. Q100: What are the practical consequences of diffs in Smalltalk/C++
  359.    inheritance?
  360. Q101: Do you need to learn a "pure" OOPL before you learn C++?
  361. Q102: What is the NIHCL?  Where can I get it?
  362.  
  363. SECTION 16: Reference and value semantics
  364. Q103: What is value and/or reference semantics, and which is best in C++?
  365. Q104: What is "virtual data," and how-can / why-would I use it in C++?
  366. Q105: What's the difference between virtual data and dynamic data?
  367. Q106: Should I normally use pointers to freestore allocated objects for my
  368.    data members, or should I use "composition"?
  369. Q107: What are relative costs of the 3 performance hits associated with
  370.    allocating member objects from the freestore?
  371. Q108: Are "inline virtual" member fns ever actually "inlined"?
  372. Q109: Sounds like I should never use reference semantics, right?
  373. Q110: Does the poor performance of ref semantics mean I should pass-by-value?
  374.  
  375. ========== POSTING #4 ==========
  376.  
  377. SECTION 17: Linkage-to/relationship-with C
  378. Q111: How can I call a C function "f(int,char,float)" from C++ code?
  379. Q112: How can I include a C header file in my C++ code?
  380. Q113: How can I modify a C header file so it can be #included in C++ code?
  381. Q114: How can I create a C++ function "f(int,char,float)" that is callable by
  382.    my C code?
  383. Q115: Why's the linker giving errors for C/C++ fns being called from C++/C
  384.    fns?
  385. Q116: How can I pass an object of a C++ class to/from a C function?
  386. Q117: Can my C function access data in an object of a C++ class?
  387. Q118: Why do I feel like I'm "further from the machine" in C++ as opposed to
  388.    C?
  389.  
  390. SECTION 18: Pointers to member functions
  391. Q119: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?
  392. Q120: How do I pass a ptr to member fn to a signal handler, X event callback,
  393.    etc?
  394. Q121: Why do I keep getting compile errors (type mismatch) when I try to use a
  395.    member function as an interrupt service routine? 
  396. Q122: Why am I having trouble taking the address of a C++ function?
  397. Q123: How do I declare an array of pointers to member functions?
  398.  
  399. SECTION 19: Container classes and templates
  400. Q124: How can I build a <favorite container> of objects of different types?
  401. Q125: How can I insert/access/change elements from a linked
  402.    list/hashtable/etc?
  403. Q126: What's the idea behind "templates"?
  404. Q127: What's the syntax / semantics for a "function template"?
  405. Q128: What's the syntax / semantics for a "class template"?
  406. Q129: What is a "parameterized type"?
  407. Q130: What is "genericity"?
  408.  
  409. SECTION 20: Libraries
  410. Q131: Where can I get a copy of "STL"?
  411. Q132: Where can I get help on how to use STL?
  412. Q133: Where can I ftp the code that accompanies "Numerical Recipes"?
  413. Q134: Why is my executable so large?
  414.  
  415. SECTION 21: Nuances of particular implementations
  416. Q135: GNU C++ (g++) produces big executables for tiny programs; Why?
  417. Q136: Is there a yacc-able C++ grammar?
  418. Q137: What is C++ 1.2?  2.0?  2.1?  3.0?
  419. Q138: If name mangling was standardized, could I link code compiled with
  420.    compilers from different compiler vendors?
  421.  
  422. SECTION 22: Miscellaneous technical and environmental issues
  423. SUBSECTION 22A: Miscellaneous technical issues:
  424. Q139: Why are classes with static data members getting linker errors?
  425. Q140: What's the difference between the keywords struct and class?
  426. Q141: Why can't I overload a function by its return type?
  427. Q142: What is "persistence"?  What is a "persistent object"?
  428. Q143: Why is floating point so inaccurate?  Why doesn't this print 0.43?
  429. SUBSECTION 22B: Miscellaneous environmental issues:
  430. Q144: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
  431. Q145: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
  432. Q146: Where can I access "tgrind," a pretty printer for C++/C/etc source?
  433. Q147: Is there a C++-mode for GNU emacs?  If so, where can I get it?
  434. Q148: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?
  435. Q149: Why does my DOS C++ program says "Sorry: floating point code not
  436.    linked"?
  437. Q150: Why does my BC++ Windows app crash when I'm not running the BC45 IDE?
  438. ==============================================================================
  439. SUBSECTION 1C: Nomenclature, Acronyms, and Common Abbreviations
  440. ==============================================================================
  441.  
  442. Here are a few of the abbreviations/acronyms/etc used in comp.lang.c++ and in
  443. this on-line document:
  444.  
  445.     Term    Meaning
  446.     ====    ===========
  447.     C++ARM    C++ Annotated Reference Manual (an Addison-Wesley book)
  448.     C++PL2    C++ Programming Language Second Ed. (an Addison-Wesley book)
  449.     fn        function
  450.     fns        functions
  451.     method    an alternate term for "member function"
  452.     OO        object-oriented
  453.     OOP        object-oriented programming
  454.     OOPL    object-oriented programming language
  455.     param    parameter
  456.     ptr        pointer, a C/C++ construct declared by:  int * p;
  457.     ref        reference, a C++ construct declared by:  int & r;
  458.     RTTI    Run-time type identification
  459.  
  460. ==============================================================================
  461. SECTION 2: How should I post something? (READ BEFORE POSTING)
  462. ==============================================================================
  463.  
  464. Q4: Which newsgroup should I post my questions?
  465.  
  466. Comp.lang.c++ is the best place to discuss the C++ language itself (e.g.,
  467. C++ code design, syntax, style).  Other newsgroups exist for discussion of
  468. topics which are specific to a particular system (e.g., MS Windows or UNIX)
  469. or topics which are not directly related to the C++ language (e.g., how to
  470. use your compiler).  Here's a list of some very active newsgroups and
  471. excerpts from their Frequently Asked Questions lists.  These excerpts
  472. should give you an idea of the type of topics frequently discussed there.
  473.  
  474.   comp.os.ms-windows.programmer.tools
  475.      This group is intended for discussions about the selection and use of
  476.      tools for Windows software development.
  477.   comp.os.ms-windows.programmer.misc
  478.      This group is for all other discussions about Windows software
  479.      development.
  480.   [There's one FAQ list for all the comp.os.ms-windows.programmer.* groups]
  481.      FAQ 5.7.1.  Accessing C++ classes in a DLL
  482.      FAQ 6.1.1.  A dialog as an MDI child window [with OWL]
  483.      FAQ 6.2.1.  Disabled menu choices become enabled [with MFC]
  484.      FAQ 8.1.5.  Using STRICT with windows.h
  485.      FAQ 10.  A programmer's bibliography
  486.  
  487.   comp.os.msdos.programmer
  488.      Much of the traffic is about language products (chiefly from Borland
  489.      and Microsoft).
  490.      FAQ 301. How can I read a character without [waiting for] the Enter key?
  491.      FAQ 412. How can I read, create, change, or delete the volume label?
  492.      FAQ 504. How do I configure a COM port and use it to transmit data?
  493.      FAQ 602. How can a C program send control codes to my printer?
  494.      FAQ 606. How can I find the Microsoft mouse position and button status?
  495.      FAQ 707. How can I write a TSR (terminate-stay-resident) utility?
  496.      FAQ B0. How can I contact [Borland, Microsoft]?
  497.      [note: this FAQ is not available at rtfm.mit.edu; it is at Simtel
  498.             (e.g., oak.oakland.edu) in /pub/msdos/info/faqp*.zip and Garbo
  499.             (garbo.uwasa.fi) in /pc/doc-net/faqp*.zip]
  500.   comp.os.msdos.programmer.turbovision [Borland's character-mode framework]
  501.  
  502.   comp.unix.programmer
  503.      FAQ 4.5)  How do I use popen() to open a process for reading AND writing?
  504.      FAQ 4.6)  How do I sleep() in a C program for less than one second?
  505.  
  506.   comp.unix.solaris (covers SunOS 4.x and Solaris)
  507.      FAQ 4)  Signal Primer
  508.      FAQ 5)  Waiting for Children to Exit
  509.  
  510.   gnu.g++.help
  511.      FAQ: Where can I find a demangler?
  512.      FAQ: Getting gcc/g++ binaries for Solaris 2.x
  513.      FAQ: What documentation exists for g++ 2.x?
  514.   gnu.g++.bug [bug reports for g++ -- see the g++ docs]
  515.  
  516.   comp.lang.c
  517.      FAQ 1.10: I'm confused.  NULL is guaranteed to be 0, but the null
  518.                pointer is not?
  519.      FAQ 2.3:  So what is meant by the "equivalence of pointers and
  520.                arrays" in C?
  521.      FAQ 4.2:  [Why doesn't "printf("%d\n," i++ * i++);" work?]
  522.      FAQ 7.1:  How can I write a function that takes a variable number
  523.                of arguments? [stdarg.h or varargs.h]
  524.      FAQ 10.4: How do I declare an array of pointers to functions returning
  525.                pointers to functions returning pointers to characters?
  526.  
  527. Also check out the newsgroups comp.graphics, comp.sources.wanted,
  528. comp.programming, and comp.object (its FAQ is an excellent introduction and
  529. overview of OOP terms and concepts).  Remember that comp.std.c++ is for
  530. discussion DIRECTLY related to the evolving ANSI/ISO C++ Standard (see more
  531. below). 
  532.  
  533. There's rarely a need to crosspost a question to one of the above
  534. newsgroups and comp.lang.c++ (readers in the system-specific newsgroups
  535. aren't programming in machine language, ya know).  It's bad netiquette to
  536. crosspost widely because your problem is "really important."  If you don't
  537. get an answer in the "right" newsgroup and feel you must post here, at
  538. least consider redirecting followups back to the appropriate newsgroup.
  539.  
  540. Before posting a question to any newsgroup you should read it's FAQ list.
  541. An answer to your question is likely to be there, saving you the time of
  542. posting and saving thousands of other people around the world the time of
  543. reading your question.  People answering a FAQ are likely to be annoyed for
  544. having to answer it for the umpteenth time, or they're likely to be giving
  545. you a wrong or incomplete answer since they haven't read the FAQ either.
  546.  
  547. Frequently Asked Questions lists are available 24-hours a day via anonymous
  548. ftp (rtfm.mit.edu in /pub/usenet/comp.what.ever) or e-mail server (send a
  549. message with the line "help" to mail-server@rtfm.mit.edu).  See the article
  550. "Introduction to the *.answers newsgroups" in the newsgroup news.answers or
  551. news.announce.newusers (which contains many other must-read articles) for
  552. more information.
  553.  
  554. ==============================================================================
  555.  
  556. Q5: How do I post a question about code that doesn't work correctly?
  557.  
  558. Here's some guidelines you should follow that will help people reading
  559. comp.lang.c++ help you with an answer to your programming problem.
  560.  
  561. 1. Please read the previous FAQ to make sure that your question is about the
  562.    C++ language and not a question about programming on your system (e.g.,
  563.    graphics, printers, devices, etc.) or using your compilation
  564.    environment (e.g., "the IDE crashes when I...," "how do you turn off
  565.    warnings about...," "how do I tell it to link my libraries").  If you
  566.    want to know why your virtual CmOk() function isn't being called in
  567.    your OWL program, your question is probably more appropriate in the
  568.    Windows programming newsgroup.  If you can write a small stand-alone
  569.    program which exhibits the same undesired compiler error or behavior
  570.    as your OWL program, by all means post here in comp.lang.c++ since C++
  571.    programmers using other systems could be of help.
  572.  
  573. 2. Be descriptive in the subject line.  "C++ problem" leaves a lot to the
  574.    imagination.  "Problem new'ing a multi-dimensional array" is good.
  575.    Refrain from exclamation points, cries for HELPPP, and the once funny
  576.    "SEX SEX SEX."  If you think the problem is specific to your compiler,
  577.    you might want to mention the compiler/version in the subject line.
  578.  
  579. 3. Post code that is complete and compilable.  It's extremely difficult
  580.    to debug or reconstruct a program from a human language description.
  581.    By "complete code" I mean that any types and functions used are
  582.    declared, headers are #include'd, etc.  Please strip the code down to
  583.    the bare essentials.  We don't need a program that does something
  584.    useful at run-time, or even links.  We just need to be able to
  585.    reproduce the undesired compiler error (possibly on a different
  586.    compiler).  By "compilable code" I mean that it doesn't contain a
  587.    bunch of uncommented ellipses or line numbers at the beginning of each
  588.    line:
  589.  
  590.     14:    #include <iostream.h>
  591.     15:    class Foo { ... };  // this is annoying
  592.  
  593.    Try to organize the code into one linear program instead of making us cut
  594.    out and create header files.  Be very careful if you are typing the code
  595.    into your article -- it's often difficult to tell whether something is a
  596.    typo or the real cause of the problem.  Try using your editor's
  597.    cut&paste or "insert file" feature instead.
  598.  
  599. 4. Mention what compiler, compiler version, and system you're using.  I
  600.    know, I just said that system-specific questions should go to a
  601.    system-specific newsgroup, but compiler information is often very
  602.    useful in diagnosing the problem: ("yeah, I remember Acme 1.2 having
  603.    lots of problems in this area").  It also warns other users of that
  604.    compiler about possible bugs.
  605.  
  606. 5. Show us the exact compiler and linker options and libraries you used
  607.    when building your program.
  608.  
  609. 6. List the exact error message and where the error was given.  "Virtual
  610.    functions don't work" doesn't tell us whether its a compile-, link-, or
  611.    run-time problem.  If the problem is at run-time, give a good
  612.    description of the behavior and any relevant information about your
  613.    system setup.
  614.  
  615. 7. Include a working e-mail address in your signature.  If the address in
  616.    given your article's "From:" line is not correct, please notify your
  617.    system administrator.  Until it is fixed, add a "Reply-To:" line to
  618.    your headers that uses your correct e-mail address.
  619.  
  620. 8. Please read the rest of this FAQ -- chances are your problem, or a
  621.    closely related problem, is discussed here.  Thank you and I hope these
  622.    suggestions help you find a solution to your problem.
  623.  
  624. ==============================================================================
  625. SECTION 3: Environmental/managerial issues
  626. ==============================================================================
  627.  
  628. Q6: What is OOP?  What is C++?
  629.  
  630. OO programming techniques are the best way we know of to develop large, complex
  631. software applications and systems.
  632.  
  633. C++ is an OO programming language.  C++ can be used both as an OOPL and simply
  634. "as a better C."  However if you use it "as a better C," don't expect to get
  635. the benefits of object-oriented programming.
  636.  
  637. OO hype: the software industry is "failing" to meet demands for large, complex
  638. software systems.  But this "failure" is actually due to our SUCCESSES: our
  639. successes have propelled users to ask for more.  Unfortunately we created a
  640. market hunger that the "structured" analysis, design and programming techniques
  641. couldn't satisfy.  This required us to create a better paradigm.
  642.  
  643. ==============================================================================
  644.  
  645. Q7: Is C++ better than Ada? (or Pascal, C, FORTRAN, Visual Basic, or any other
  646.    language?)
  647.  
  648. This question generates much MUCH more heat than light.  Please read this
  649. before posting some variant of this question.
  650.  
  651. In 99% of the cases, programming language selection is dominated by business
  652. considerations, NOT by technical considerations.  Things that REALLY end up
  653. mattering are things like availability of a programming environment for the
  654. development machine, availability of runtime environment(s) for the deployment
  655. machine(s), licensing/legal issues of the runtime and/or development
  656. environments, availability of trained developers, availability of consulting
  657. services, and corporate culture/politics.  These business considerations
  658. generally play a much greater role than compile time performance, runtime
  659. performance, static vs. dynamic typing, static vs. dynamic binding, etc.
  660.  
  661. Therefore anyone who argues in favor of one language over another in a purely
  662. technical manner (i.e., who ignores the dominant business issues) exposes
  663. themselves as a techie weenie, and deserves not to be heard.
  664.  
  665. ==============================================================================
  666.  
  667. Q8: What are some advantages of C++?
  668.  
  669. GROWTH OF C++: C++ is by far the most popular OOPL.  The number of C++ users is
  670. doubling every 7.5 to 9 months.  Knowing C++ is a good resume-stuffer (but use
  671. it as an OOPL rather than just as a better C).
  672.  
  673. ENCAPSULATION: Hiding our data structures allows us to change one chunk of a
  674. system without breaking other chunks.  We provide our software chunks (we call
  675. them "classes") with safe interfaces.  Users of a chunk use its interface only.
  676. The relatively volatile "implementation" of this interface is "encapsulated"
  677. ("put into a capsule") to prevent users from becoming reliant on its temporary
  678. decisions.  In simple C, this was done by making a module's data "static", thus
  679. preventing another module from accessing our module's bits.
  680.  
  681. MULTIPLE INSTANCES: The typical C solution to encapsulation (see above) doesn't
  682. support multiple instances of the data (it's hard to make multiple instances of
  683. a module's "static" data).  If we needed multiple instances in C, we used a
  684. "struct" (but this doesn't support "encapsulation").  In C++, we can have both
  685. multiple instances and encapsulation via a "class": the "public" part of a
  686. class contains the class's interface (normally these are a special kind of
  687. function called a "member function"), and the "private" part of a class
  688. contains the class's implementation (typically these are where the bits live).
  689.  
  690. INLINE FUNCTION CALLS: In straight C, you can achieve "encapsulated structs" by
  691. putting a "void*" in a struct (the access functions use pointer casts).  This
  692. forfeits type safety, and also imposes a function call to access even trivial
  693. fields of the struct (if you allowed direct access to the struct's fields, the
  694. underlying data structure would be difficult to change since too many chunks
  695. would RELY on it being the "old" way).  Function call overhead is small, but
  696. can add up.  C++ classes allow function calls to be expanded "inline," so you
  697. have: the 1) safety of encapsulation, 2) convenience of multiple instances, 3)
  698. speed of direct access.  Furthermore the parameter types of these inline
  699. functions are checked by the compiler, an improvement over C's #define macros.
  700.  
  701. OVERLOADING OPERATORS: C++ lets you overload the standard operators on a class,
  702. which lets users exploit their intuition (e.g., "myString + yourString" might
  703. do string concatenation, "myDate++" might increment the date, "z1 * z2" might
  704. multiply complex numbers z1 and z2, "a[i]" might access the "i"th element of
  705. the "linked list" called "a", etc.  You can even have "smart pointers" that
  706. could "point" to a disk record or wherever ("x = *p" could "dereference" such a
  707. pointer, which could seek to the location on disk where p "points" and return
  708. its value").  This allows users to program in the language of the problem
  709. domain rather than in the language of the machine.
  710.  
  711. INHERITANCE: We still have just scratched the surface.  In fact, we haven't
  712. even gotten to the "object-oriented" part yet!  Suppose you have a Stack data
  713. type with operations push, pop, etc.  Suppose you want an InvertableStack,
  714. which is "just like" Stack except it also has an "invert" operation.  In "C"
  715. style, you'd have to either (1) modify the existing Stack module (trouble if
  716. "Stack" is being used by others), or (2) copy Stack into another file and text
  717. edit that file (results in lots of code duplication, another chance to break
  718. something tricky in the Stack part of InvertableStack, and especially twice as
  719. much code to maintain).  C++ provides a much cleaner solution: inheritance.
  720. You say "InvertableStack inherits everything from Stack, and InvertableStack
  721. adds the invert operation."  Done.  Stack itself remains "closed" (untouched,
  722. unmodified), and InvertableStack doesn't duplicate the code for push/pop/etc.
  723.  
  724. POLYMORPHISM AND DYNAMIC BINDING: The real power of OOP isn't just inheritance,
  725. but is the ability to pass an InvertableStack around as if it actually were a
  726. Stack.  This is "safe" since (in C++ at least) the is-a relation follows public
  727. inheritance (i.e., a InvertableStack is-a Stack that can also invert itself).
  728. Polymorphism and dynamic binding are easiest to understand from an example, so
  729. here's a "classic": a graphical draw package might deal with Circles, Squares,
  730. Rectangles, general Polygons, and Lines.  All of these are Shapes.  Most of the
  731. draw package's functions need a "Shape" parameter (as opposed to some
  732. particular kind of shape like Square).  E.g., if a Shape is picked by a mouse,
  733. the Shape might get dragged across the screen and placed into a new location.
  734. Polymorphism and dynamic binding allow the code to work correctly even if the
  735. compiler knows only that the parameter is a "Shape" without knowing the exact
  736. kind of Shape it is.  Furthermore suppose the "pick_and_drag(Shape*) function
  737. just mentioned was compiled on Tuesday, and on Wednesday you decide to add the
  738. Hexagon shape.  Strange as it sounds, pick_and_drag() will still work with
  739. Hexagons, even though the Hexagon didn't even exist when pick_and_drag() was
  740. compiled!!  (it's not really "amazing" once you understand how the C++ compiler
  741. does it -- but it's still very convenient!)
  742.  
  743. ==============================================================================
  744.  
  745. Q9: Who uses C++?
  746.  
  747. Lots and lots of companies and government sites.  Lots.
  748.  
  749. Statistically, 5 people became new C++ programmers while you read the words of
  750. the previous FAQ.
  751.  
  752. ==============================================================================
  753.  
  754. Q10: Are there any C++ standardization efforts underway?
  755.  
  756. Yes; ANSI (American) and ISO (International) groups are working closely with
  757. each other.  The ANSI-C++ committee is called "X3J16".  The ISO C++ standards
  758. group is called "WG21".  The major players in the ANSI/ISO C++ standards
  759. process includes just about everyone:
  760.  
  761. AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, etc ad nauseum.
  762. About 70 people attend each meeting.  People come from USA, UK, Japan, Germany,
  763. Sweden, Denmark, France, ... (all have "local" committees sending official
  764. representatives and conducting "local" meetings).
  765.  
  766. ==============================================================================
  767.  
  768. Q11: Where can I get a copy of the latest ANSI/ISO-C++ draft standard?
  769.  
  770. The ISO Committee Draft for C++ and the ANSI C++ Draft (the document that
  771. is going out for public review) is available from:
  772.     http://www.cygnus.com/~mrs/wp-draft
  773.  
  774. You can also get Postscript and Adobe Acrobat versions from:
  775.     ftp://research.att.com/dist/c++std/WP
  776.     ftp://ftp.maths.warwick.ac.uk:/pub/c++/std/WP
  777.     ftp://ftpt.su.edu.au:/pub/C++/CommitteeDraft
  778.  
  779. You can get HTML and ASCII versions:
  780.     ftp://ftp.cygnus.com/pub/g++
  781.  
  782. You can also get a paper copy from:
  783.     X3 Secretariat
  784.     1250 Eye Street NW
  785.     Suite 200
  786.     Washington, DC  20005
  787.     202-626-5738
  788.  
  789. You can also order via email:
  790.     lbarra@itic.nw.dc.us (Lynn Barra)
  791.  
  792. Ask for the latest version of "Draft Proposed American National Standard for
  793. Information Systems -- Programming Language C++" which is document number
  794. CD14882.  It is typically shipped 2-day FedEx (within the continental US), so
  795. people usually get it quickly.
  796.  
  797. ==============================================================================
  798.  
  799. Q12: Is C++ backward compatible with ANSI-C?
  800.  
  801. Almost.
  802.  
  803. C++ is as close as possible to compatible with C, but no closer.  In practice,
  804. the major difference is that C++ requires prototypes, and that "f()" declares a
  805. function that takes no parameters (in C, "f()" is the same as "f(...)").  There
  806. are some very subtle differences as well, like sizeof('x') is equal to
  807. sizeof(char) in C++ but is equal to sizeof(int) in C.  Also, C++ puts structure
  808. "tags" in the same namespace as other names, whereas C requires an explicit
  809. "struct" (the "typedef struct Fred Fred" technique still works, but is
  810. redundant in C++).
  811.  
  812. ==============================================================================
  813.  
  814. Q13: How long does it take to learn C++?
  815.  
  816. Companies like Paradigm Shift, Inc. successfully teach standard industry "short
  817. courses", where we compress a university semester course into one 40hr work
  818. week.  However true mastery takes experience; there's no substitute for time.
  819. Hands-on projects are essential, since they allow concepts to "gel."
  820.  
  821. It takes 6-12 months to become proficient in C++/OOP.  Less if the developers
  822. have easy access to a "local" body of experts, more if there isn't a "good"
  823. general purpose C++ class library available.  To become one of these experts
  824. who can mentor others takes around 3 years.
  825.  
  826. Some people never make it.  You don't have a chance unless you are teachable
  827. and have personal drive.  As a bare minimum on "teachability," you have to be
  828. able to admit when you've are wrong.  As a bare minimum on "drive," you must
  829. be willing to put in some extra hours (changing the way you think [a paradigm
  830. shift] is a LOT more painful than learning a few new facts).
  831.  
  832. ==============================================================================
  833. SECTION 4: Basics of the paradigm
  834. ==============================================================================
  835.  
  836. Q14: What is a class?
  837.  
  838. The fundamental building block of OO software.
  839.  
  840. A class defines a data type, much like a struct would be in C.  In a computer
  841. science sense, a type consists of both a set of states AND a set of operations
  842. which transition between those states.  Thus "int" is a "type" because it has
  843. both a set of states AND it has operations like "add two ints" or "int*int,"
  844. etc.  In exactly the same way, a "class" provides a set of (usually public)
  845. operations, and a set of (usually non-public) data bits representing the
  846. abstract values that instances of the type can have.  From a C language
  847. perspective, a class is a struct whose members default to "private".
  848.  
  849. Think of "int" as a class that has methods called "operator++", etc.
  850.  
  851. ==============================================================================
  852.  
  853. Q15: What is an object?
  854.  
  855. A region of storage with associated semantics.
  856.  
  857. After the declaration "int i;" we say that "i is an object of type int."  In
  858. C++/OOP, "object" usually means "an instance of a class."  Thus a class defines
  859. the behavior of possibly many objects (instances).
  860.  
  861. ==============================================================================
  862.  
  863. Q16: What is a reference?
  864.  
  865. An alias (an alternate name) for an object.
  866.  
  867. References are frequently used for pass-by-reference:
  868.  
  869.     void swap(int& i, int& j)
  870.     {
  871.       int tmp = i;
  872.       i = j;
  873.       j = tmp;
  874.     }
  875.  
  876.     main()
  877.     {
  878.       int x, y;
  879.       //...
  880.       swap(x,y);
  881.     }
  882.  
  883. Here "i" and "j" are aliases for main's "x" and "y" respectively.  In other
  884. words, "i" IS "x" -- not a pointer to "x", nor a copy of "x", but "x" itself.
  885. Anything you do to "i" gets done to "x", and vise versa.
  886.  
  887. Underneath it all, references are typically implemented by pointers.  The
  888. effect is as if you used the C style pass-by-pointer, but the "&" is moved from
  889. the caller into the callee, and you eliminate all the "*"s.
  890.  
  891. ==============================================================================
  892.  
  893. Q17: What happens if you assign to a reference?
  894.  
  895. You change the referrent (the object to which the reference refers).
  896.  
  897. Remember: the reference IS the referrent, so changing the reference changes the
  898. referrent (a reference is an "Lvalue" [something that can appear on the
  899. "L"eft-hand-side of an assignment statement] for the referrent).
  900.  
  901. This insight can be pushed a bit farther by allowing references to be RETURNED.
  902. This allows function calls on the left hand side of an assignment statement,
  903. which is useful with operator overloading.
  904.  
  905. ==============================================================================
  906.  
  907. Q18: How can you reseat a reference to make it refer to a different object?
  908.  
  909. No way.
  910.  
  911. Unlike a pointer, once a reference is bound to an object, it can NOT be
  912. "reseated" to another object.  The reference itself isn't an object (it has no
  913. address; taking the address of a reference gives you the address of the
  914. referrent; remember: the reference IS its referrent).
  915.  
  916. You can't separate the reference from the referent.
  917.  
  918. ==============================================================================
  919.  
  920. Q19: When should I use references, and when should I use pointers?
  921.  
  922. Use references when you can, and pointers when you have to.
  923.  
  924. References are usually preferred over ptrs whenever you don't need "reseating"
  925. (see previous FAQ).  This usually means that references are most useful in a
  926. class's public interface.  References typically appear on the skin of an
  927. object, and pointers on the inside.
  928.  
  929. The exception to the above is where a function's parameter or return value
  930. needs a "sentinel" reference.  This is usually best done by returning/taking a
  931. pointer, and giving the NULL pointer this special significance (references
  932. should always alias objects, not a dereferenced NULL ptr).
  933.  
  934. NOTE: Old line C programmers sometimes don't like references since they provide
  935. reference semantics that isn't explicit in the caller's code.  After some C++
  936. experience, however, one quickly realizes this is a form of information hiding,
  937. which is an asset rather than a liability.  E.g., programmers should write code
  938. in the language of the problem rather than the language of the machine.
  939.  
  940. ==============================================================================
  941.  
  942. Q20: What's the deal with inline functions?
  943.  
  944. An inline function is a function whose code gets inserted into the caller's
  945. code stream.  Like a macro, inline functions improve performance by avoiding
  946. the overhead of the call itself and (especially!) by the compiler being able to
  947. optimize THROUGH the call ("procedural integration").  Unlike macros, inline
  948. functions avoid infamous macro errors by evaluating all arguments exactly once
  949. (the "call" is semantically like a regular function call, only faster).  Also
  950. unlike macros, argument types are checked, and necessary conversions are
  951. performed correctly (macros are bad for your health; don't use them unless you
  952. absolutely have to).
  953.  
  954. Beware that overuse of inline functions can cause code bloat, which can in
  955. turn have a negative performance impact in paging environments.
  956.  
  957. They are declared by using the "inline" keyword when the function is defined:
  958.  
  959.     inline void f(int i, char c) { /*...*/ }
  960.  
  961. or by including the function definition itself within a class:
  962.  
  963.     class Fred {
  964.     public:
  965.       void f(int i, char c) { /*...*/ }
  966.     };
  967.  
  968. or by defining the member function as "inline" outside the class:
  969.  
  970.     class Fred {
  971.     public:
  972.       void f(int i, char c);
  973.     };
  974.  
  975.     inline void Fred::f(int i, char c) { /*...*/ }
  976.  
  977. ==============================================================================
  978. SECTION 5: Constructors and destructors
  979. ==============================================================================
  980.  
  981. Q21: What's the deal with constructors?
  982.  
  983. Constructors build objects from dust.
  984.  
  985. Constructors are like "init functions"; they turn a pile of arbitrary bits into
  986. a living object.  Minimally they initialize internally used fields.  They may
  987. also allocate resources (memory, files, semaphores, sockets, etc).
  988.  
  989. "ctor" is a typical abbreviation for constructor.
  990.  
  991. ==============================================================================
  992.  
  993. Q22: How can I make a constructor call another constructor as a primitive?
  994.  
  995. No way.
  996.  
  997. Dragons be here: if you call another constructor, the compiler initializes a
  998. temporary local object; it does NOT initialize "this" object.  You can combine
  999. both constructors by using a default parameter, or you can share their common
  1000. code in a private "init()" member function.
  1001.  
  1002. ==============================================================================
  1003.  
  1004. Q23: What's the deal with destructors?
  1005.  
  1006. A destructor gives an object its last rites.
  1007.  
  1008. Destructors are used to release any resources allocated by the object.  E.g., a
  1009. Lock class might lock a semaphore, and the destructor will release that
  1010. semaphore.  The most common example is when the constructor uses "new", and the
  1011. destructor uses "delete".
  1012.  
  1013. Destructors are a "prepare to die" method.  They are often abbreviated "dtor".
  1014.  
  1015. ==============================================================================
  1016. SECTION 6: Operator overloading
  1017. ==============================================================================
  1018.  
  1019. Q24: What's the deal with operator overloading?
  1020.  
  1021. It allows users of your classes to use intuitive syntax.
  1022.  
  1023. Operator overloading allows C/C++ operators to have user-defined meanings on
  1024. user-defined types (classes).  They're syntactic sugar for function calls:
  1025.  
  1026.     class Fred {
  1027.     public:
  1028.       //...
  1029.     };
  1030.  
  1031.     #if 0
  1032.       Fred add(Fred, Fred);        //without operator overloading
  1033.       Fred mul(Fred, Fred);
  1034.     #else
  1035.       Fred operator+(Fred, Fred);    //with operator overloading
  1036.       Fred operator*(Fred, Fred);
  1037.     #endif
  1038.  
  1039.     Fred f(Fred a, Fred b, Fred c)
  1040.     {
  1041.       #if 0
  1042.         return add(add(mul(a,b), mul(b,c)), mul(c,a));  //without...
  1043.       #else
  1044.         return a*b + b*c + c*a;                         //with...
  1045.       #endif
  1046.     }
  1047.  
  1048. ==============================================================================
  1049.  
  1050. Q25: What operators can/cannot be overloaded?
  1051.  
  1052. Most can be overloaded. The only C operators that can't be are "." and "?:"
  1053. (and "sizeof," which is technically an operator).  C++ adds a few of its own
  1054. operators, most of which can be overloaded except "::" and ".*".
  1055.  
  1056. Here's an example of the subscript operator (it returns a reference).  First
  1057. withOUT operator overloading:
  1058.  
  1059.     class Array {
  1060.     public:
  1061.       #if 0
  1062.         int& elem(unsigned i) { if (i>99) error(); return data[i]; }
  1063.       #else
  1064.         int& operator[] (unsigned i) { if (i>99) error(); return data[i]; }
  1065.       #endif
  1066.     private:
  1067.       int data[100];
  1068.     };
  1069.  
  1070.     main()
  1071.     {
  1072.       Array a;
  1073.  
  1074.       #if 0
  1075.         a.elem(10) = 42;
  1076.         a.elem(12) += a.elem(13);
  1077.       #else
  1078.         a[10] = 42;
  1079.         a[12] += a[13];
  1080.       #endif
  1081.     }
  1082.  
  1083. ==============================================================================
  1084.  
  1085. Q26: Can I create a "**" operator for "to-the-power-of" operations?
  1086.  
  1087. Nope.
  1088.  
  1089. The names of, precedence of, associativity of, and arity of operators is fixed
  1090. by the language.  There is no "**" operator in C++, so you cannot create one
  1091. for a class type.
  1092.  
  1093. If you're in doubt, consider that "x ** y" is the same as "x * (*y)" (in other
  1094. words, the compiler assumes "y" is a pointer).  Besides, operator overloading
  1095. is just syntactic sugar for function calls.  Although this particular syntactic
  1096. sugar can be very sweet, it doesn't add anything fundamental.  I suggest you
  1097. overload "pow(base,exponent)" (a double precision version is in <math.h>).
  1098.  
  1099. BTW: operator^ can work, except it has the wrong precedence and associativity.
  1100.  
  1101. ==============================================================================
  1102. SECTION 7: Friends
  1103. ==============================================================================
  1104.  
  1105. Q27: What is a "friend"?
  1106.  
  1107. Something to allow your class to grant access to another class or function.
  1108.  
  1109. Friends can be either functions or other classes.  A class grants access
  1110. privileges to its friends.  Normally a developer has political and technical
  1111. control over both the friends and methods of a class (else you need permission
  1112. from the owner of the other pieces when you want to update your class).
  1113.  
  1114. ==============================================================================
  1115.  
  1116. Q28: Do "friends" violate encapsulation?
  1117.  
  1118. If they're used properly, they actually ENHANCE encapsulation.
  1119.  
  1120. You often need to split a class in half when the two halves will have different
  1121. numbers of instances or different lifetimes.  In these cases, the two halves
  1122. usually need direct access to each other (the two halves USED to be in the same
  1123. class, so you haven't INCREASED the number of methods that have direct access
  1124. to a data structure; you've simply MOVED some of those methods).  The safest
  1125. way to implement this is to make the two halves friends of each other.
  1126.  
  1127. If you use friends like just described, you'll keep private things private.  In
  1128. a naive effort to avoid using friendship in situations like the above, many
  1129. people actually destroy encapsulation by either using public data (grotesque!),
  1130. or by making the data accessible between the halves via public get/set methods.
  1131. Having a public get and set method for a private datum is ok only when the
  1132. private datum "makes sense" from outside the class (from a user's perspective).
  1133. In many cases, these get/set methods are almost as bad as public data: they
  1134. hide (only) the NAMES of the private data members, but they don't hide the
  1135. existence of the private data members.
  1136.  
  1137. Similarly, if you use friend functions as a syntactic variant of a class's
  1138. public access functions, they don't violate encapsulation any more than a
  1139. member function violates encapsulation.  In other words, a class's friends and
  1140. members ARE the encapsulation barrier, as defined by the class itself.
  1141.  
  1142. ==============================================================================
  1143.  
  1144. Q29: What are some advantages/disadvantages of using friend functions?
  1145.  
  1146. They provide a degree of freedom in the interface design options.
  1147.  
  1148. Member fns and friend fns are equally privileged (100% vested).  The major
  1149. difference is that a friend function is called like "f(x)", while a member is
  1150. called like "x.f()".  Thus friend fns allow the class's designer to select
  1151. the syntax that is deemed most readable, which lowers maintenance costs.
  1152.  
  1153. The major disadvantage of friend functions is that they require an extra line
  1154. of code when you want dynamic binding.  To get the effect of a virtual friend,
  1155. the friend function should call a hidden (usually "protected:") virtual member
  1156. fn; e.g., "void f(Base& b) { b.do_f(); }".  Derived classes override the hidden
  1157. virtual member function ("void Derived::do_f()"), NOT the friend function.
  1158.  
  1159. ==============================================================================
  1160.  
  1161. Q30: What does it mean that "friendship is neither inherited nor transitive"?
  1162.  
  1163. The privileges of friendship aren't inherited: derived classes of a friend
  1164. aren't necessarily friends (I may declare you as my friend, but that doesn't
  1165. mean I necessarily trust your kids).  If class "Base" declares "f()" to be a
  1166. friend, "f()" doesn't have any automatic special access rights to the extra
  1167. stuff declared in derived class, "Derived."
  1168.  
  1169. The privileges of friendship aren't transitive: friends of a friend class
  1170. aren't necessarily friends of the original class (a friend of a friend isn't
  1171. necessarily a friend).  E.g., if class "Fred" declares class "Wilma" as a
  1172. friend, and class "Wilma" declares "f()" as a friend, "f()" doesn't necessarily
  1173. have any special access rights to "Fred".
  1174.  
  1175. ==============================================================================
  1176.  
  1177. Q31: Should my class declare a member function or a friend function?
  1178.  
  1179. Use a member when you can, and a friend when you have to.
  1180.  
  1181. Sometimes friends are syntactically better (e.g., in class "Fred", friend fns
  1182. allow the "Fred" param to be second, while members require it to be first).
  1183. Another good use of friend functions are the binary infix arithmetic operators
  1184. (e.g., "aComplex + aComplex" probably should be defined as a friend rather than
  1185. a member, since you want to allow "aFloat + aComplex" as well; recall members
  1186. don't allow promotion of the left hand arg, since that would change the class
  1187. of the object that is the recipient of the member function invocation).
  1188.  
  1189. In other cases, choose a member function over a friend function.
  1190.  
  1191. ==============================================================================
  1192. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  1193. ==============================================================================
  1194.  
  1195. Q32: How can I provide printing for a "class Fred"?
  1196.  
  1197. Provide a friend operator<<:
  1198.  
  1199.     class Fred {
  1200.     public:
  1201.       friend ostream& operator<< (ostream& o, const Fred& fred)
  1202.         { return o << fred.i; }
  1203.       //...
  1204.     private:
  1205.       int i;    //just for illustration
  1206.     };
  1207.  
  1208. We use a friend rather than a member since the "Fred" parameter is second
  1209. rather than first.  Input is similar, but the signature is:
  1210.  
  1211.     istream& operator>> (istream& i, Fred& fred);
  1212.                                   // ^^^^^------- not "const Fred& fred"!
  1213.  
  1214. ==============================================================================
  1215.  
  1216. Q33: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  1217.  
  1218. Increase type safety, reduce errors, improve performance, allow extensibility,
  1219. and provide subclassability.
  1220.  
  1221. Printf is arguably not broken, and scanf is perhaps livable despite being error
  1222. prone, however both are limited with respect to what C++ I/O can do.  C++ I/O
  1223. (using "<<" and ">>") is, relative to C (using "printf()" and "scanf()"):
  1224.  
  1225.  * Type safe -- type of object being I/O'd is known statically by the compiler,
  1226.    rather than via dynamically tested via "%" fields.
  1227.  
  1228.  * Less error prone -- redundant info increases the chance of errors.  C++ I/O
  1229.    has no redundant "%" tokens to get right.
  1230.  
  1231.  * Extensible -- the C++ I/O mechanism allows new user-defined types to be
  1232.    added without breaking existing code (imagine the chaos if everyone was
  1233.    simultaneously adding new incompatible "%" fields to printf and scanf?!).
  1234.  
  1235.  * Subclassable -- ostream and istream (the C++ replacements for FILE*) are
  1236.    real classes, and hence subclassable.  This means you can have other user
  1237.    defined things that look and act like streams, yet that do whatever strange
  1238.    and wonderful things you want.  You automatically get to use the zillions of
  1239.    lines of I/O code written by users you don't even know, and they don't need
  1240.    to know about your "extended stream" class.
  1241.  
  1242. ==============================================================================
  1243.  
  1244. Q34: Why does my input seem to process past the end of file?
  1245. Because the eof state is not set until after a read is attempted past the
  1246. end of file.  That is, reading the last byte from a file does not set the
  1247. eof state.
  1248.  
  1249. If your code looks like this:
  1250.  
  1251.     int i = 0;
  1252.     while (! cin.eof())  {
  1253.       cin >> x;
  1254.       ++i;
  1255.       // work with x
  1256.     }
  1257.  
  1258. Then you have an off by one error with the count i.
  1259. What you really need is:
  1260.  
  1261.     int i = 0;
  1262.     while (cin >> x)  {
  1263.       ++i;
  1264.       // work with x
  1265.     }
  1266.  
  1267. ==============================================================================
  1268.  
  1269. Q35: Why is my program ignoring my input request after the first iteration?
  1270. Because the numerical extractor leaves non digits behind in the input buffer.
  1271.  
  1272. If your code looks like this:
  1273.  
  1274.     char name[1000];
  1275.     int age;
  1276.  
  1277.     for (;;) {
  1278.       cout << "Name: ";
  1279.       cin >> name;
  1280.       cout << "Age: ";
  1281.       cin >> age;
  1282.     }
  1283.  
  1284. What you really want is:
  1285.  
  1286.     for (;;) {
  1287.       cout << "Name: ";
  1288.       cin >> name;
  1289.       cout << "Age: ";
  1290.       cin >> age;
  1291.       cin.ignore(INT_MAX, '\n');
  1292.     }
  1293.  
  1294. ==============================================================================
  1295.  
  1296. Q36: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?
  1297.  
  1298. Here's the typical scenario that leads to this question: Someone wants to do
  1299. binary I/O using cin and cout, but their operating system (such as DOS or
  1300. OS/2) insists on doing translations on carriagereturn-linefeed pairs.
  1301.  
  1302. Here's the answer: The predefined streams cin, cout, cerr are assumed to be
  1303. text streams, and there is no standard way to cause them to be opened in
  1304. binary mode.  Closing the streams and attempting to reopen them in binary mode
  1305. might have unexpected or undesirable results.
  1306.  
  1307. On systems where it makes a difference, the implementation might provide a way
  1308. to make them binary streams, but you would have to check the manuals to find
  1309. out.
  1310.  
  1311. --
  1312. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  1313. Technology consulting services
  1314. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  1315.